package com.cuitrip.business.location.map;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.ServiceSettings;
import com.amap.api.services.poisearch.PoiItemDetail;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.cuitrip.service.R;
import com.cuitrip.util.I118Util;

import java.util.Locale;

/**
 * Created by MiJack on 2015/12/13.
 */
public class PickMapFragment extends Fragment implements PoiSearch.OnPoiSearchListener, LocationSource
        , AMapLocationListener {
    private MapView mapView;
    private AMap aMap;
    private ListView listView;
    private MapAdapter mapAdapter;
    private ImageView icon;
    //    //声明AMapLocationClient类对象
//    public AMapLocationClient mLocationClient = null;
//    //    /声明mLocationOption对象
//    public AMapLocationClientOption mLocationOption = null;
    public boolean update = true;
    final static public float zoom = 18;
    private GaoDeMapActivity mainActivity;
    private LocationManagerProxy mAMapLocationManager;
    private OnLocationChangedListener mListener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof GaoDeMapActivity) {
            mainActivity = (GaoDeMapActivity) activity;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mainActivity = null;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pick_map, container, false);
        mapView = (MapView) view.findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 必须要写
        listView = (ListView) view.findViewById(R.id.listview);
        icon = (ImageView) view.findViewById(R.id.locaIcon);
        mapAdapter = new MapAdapter();
        listView.setAdapter(mapAdapter);
//        listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                Object tag = view.getTag();
//                if (tag instanceof MapAdapter.ViewHolder == false) {
//                    return;
//                }
//                PoiItem item = ((MapAdapter.ViewHolder) tag).poiItem;
//                if (item == null) {
//                    return;
//                }
//                LatLonPoint point = item.getLatLonPoint();
//                jumpIcon();
//                update = false;
//                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(point.getLatitude(), point.getLongitude()),zoom));
//                mainActivity.selectItem(item);
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//                mainActivity.selectItem(null);
//            }
//        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Object tag = view.getTag();
                if (tag instanceof MapAdapter.ViewHolder == false) {
                    return;
                }
                PoiItem item = ((MapAdapter.ViewHolder) tag).poiItem;
                if (item == null) {
                    return;
                }
                mainActivity.selectItem(item);
                LatLonPoint point = item.getLatLonPoint();
                jumpIcon();
                update = false;
                move(point.getLatitude(), point.getLongitude());
            }
        });
        aMap = mapView.getMap();
//        //初始化定位
//        mLocationClient = new AMapLocationClient(getActivity());
////设置定位回调监听
//        mLocationClient.setLocationListener(this);
//
////初始化定位参数
//        mLocationOption = new AMapLocationClientOption();
////设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
//        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
////设置是否返回地址信息（默认返回地址信息）
//        mLocationOption.setNeedAddress(true);
////设置是否只定位一次,默认为false
//        mLocationOption.setOnceLocation(true);
////设置是否强制刷新WIFI，默认为强制刷新
//        mLocationOption.setWifiActiveScan(true);
////设置是否允许模拟位置,默认为false，不允许模拟位置
//        mLocationOption.setMockEnable(true);
////设置定位间隔,单位毫秒,默认为2000ms
//        mLocationOption.setInterval(-1);
////给定位客户端对象设置定位参数
//        mLocationClient.setLocationOption(mLocationOption);
////启动定位
//        mLocationClient.startLocation();
        aMap.getUiSettings().setZoomControlsEnabled(false);
        ServiceSettings.getInstance().setLanguage(I118Util.getLocale().getLanguage().equals(Locale.ENGLISH.getLanguage())?ServiceSettings.ENGLISH:ServiceSettings.CHINESE);
//        aMap.setLocationSource(this);// 设置定位监听
//        aMap.getUiSettings().setMyLocationButtonEnabled(false);
//        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                if (!update) {
                    update = true;
                    return;
                }
                doSearchQuery(cameraPosition.target);
                listView.clearChoices();
            }
        });
        return view;
    }

    public void showMyLocation() {
        if (aMap == null) {
            return;
        }
        //发起定位
        aMap.setLocationSource(this);
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
    }

    protected void doSearchQuery(LatLng latLng) {
        aMap.setOnMapClickListener(null);// 进行poi搜索时清除掉地图点击事件
        int currentPage = 0;
        PoiSearch.Query query = new PoiSearch.Query("", "汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施", null);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setPageSize(30);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页
        LatLonPoint lp = new LatLonPoint(latLng.latitude, latLng.longitude);
        PoiSearch poiSearch = new PoiSearch(getActivity(), query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.setBound(new PoiSearch.SearchBound(lp, 1000, true));
        poiSearch.searchPOIAsyn();// 异步搜索
    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int resultCode) {
        jumpIcon();
        if (resultCode == 0) {
            if (poiResult != null) {
                mapAdapter.setResult(poiResult);
                mainActivity.selectItem(null);
            }
        }
    }

    @Override
    public void onPoiItemDetailSearched(PoiItemDetail poiItemDetail, int i) {

    }

    private void jumpIcon() {
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(icon, "TranslationY",
                0, -getResources().getDisplayMetrics().density * 16, 0);
        objectAnimator.setDuration(800);
        objectAnimator.start();
    }

    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mAMapLocationManager == null) {
            mAMapLocationManager = LocationManagerProxy.getInstance(getActivity());
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用removeUpdates()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用destroy()方法
            // 其中如果间隔时间为-1，则定位只定一次
            // 在单次定位情况下，定位无论成功与否，都无需调用removeUpdates()方法移除请求，定位sdk内部会移除

        }
        mAMapLocationManager.requestLocationData(
                LocationProviderProxy.AMapNetwork, -1, 1000, this);
        mAMapLocationManager.setGpsEnable(false);
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mAMapLocationManager != null) {
            mAMapLocationManager.removeUpdates(this);
            mAMapLocationManager.destroy();
        }
        mAMapLocationManager = null;
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation==null){
            return;
        }
        if (mainActivity.readIntent()){
            move(amapLocation.getLatitude(),amapLocation.getLongitude());
        }
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getAMapException().getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                LatLng latLng = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
                move(amapLocation.getLatitude(), amapLocation.getLongitude());
                doSearchQuery(latLng);
            }
        }
    }

    public void changeCenter(PoiItem poiItem) {
        LatLonPoint point = poiItem.getLatLonPoint();
        move(point.getLatitude(), point.getLongitude());
    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    public void move(double lat, double lng) {
        aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), zoom));
    }

}
